/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.common.base.service.rpc;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.entity.extjs.DbModel;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.table.service.PCDataService;
import com.je.common.base.util.DataBaseUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public abstract class AbstractUpgradeModulePackageRpcServiceImpl implements UpgradeModulePackageRpcService {

    @Autowired
    private MetaService metaService;

    @Autowired
    protected CommonService commonService;

    @Autowired
    private PCDataService pcDataService;

    public static final String INSERT ="insert";
    public static final String UPDATE ="update";


    @Override
    public List<String> loadTableName() {
        return DataBaseUtils.getDataBaseTableNames();
    }

    @Override
    public void executeSql(List<String> sqlList) {
        for(String sql:sqlList){
            metaService.executeSql(sql);
        }
    }

    @Override
    public List<Map<String,Object>> executeQuerySql(String sql) {
        return  metaService.selectSql(sql);
    }

    @Override
    public List<DbModel> loadTableColumnBySql(String tableCode) {
        return pcDataService.loadTableColumnBySql(tableCode);
    }

    @Override
    public Map<String, List<DynaBean>> packageBusinessData(Map<String, String> tableAndWhereMap) {
        Map<String,List<DynaBean>> result = new HashMap<>();
        for (Map.Entry<String,String> eachEntry : tableAndWhereMap.entrySet()) {
            if(!Strings.isNullOrEmpty(eachEntry.getValue())){
                result.put(eachEntry.getKey(),metaService.select(eachEntry.getKey(), ConditionsWrapper.builder()
                        .apply(eachEntry.getValue())));
            }else{
                result.put(eachEntry.getKey(),metaService.select(eachEntry.getKey(),null));
            }
        }
        return result;
    }

    @Override
    public String installBusinessData(Map<String, List<DynaBean>> businessDataMap) {
        for (Map.Entry<String,List<DynaBean>> eachEntry : businessDataMap.entrySet()) {
            List<DynaBean> businessDataList = eachEntry.getValue();
            for(DynaBean businessData:businessDataList){
                String tableCode = eachEntry.getKey();
                String pkCode="";
                String pkValue="";
                if(StringUtil.isEmpty(pkCode)||StringUtil.isEmpty(pkValue)){
                    businessData.table(tableCode);
                     pkCode = businessData.getPkCode();
                     pkValue = businessData.getPkValue();
                }
               DynaBean dynaBean = metaService.selectOneByPk(tableCode,pkValue);
               if(dynaBean==null){
                   businessData.setStr(BeanService.KEY_TABLE_CODE,tableCode);
                   commonService.buildModelCreateInfo(businessData);
                   //commonService.generateTreeOrderIndex(businessData);
                   metaService.insert(businessData);
               }else{
                   businessData.setStr(BeanService.KEY_TABLE_CODE,tableCode);
                   commonService.buildModelModifyInfo(businessData);
                   metaService.update(businessData,ConditionsWrapper.builder().eq(pkCode,pkValue));
               }
            }

        }
        return null;
    }

    public void batchInsert(List<Map<String,Object>> list, String tableCode) {
        List<DynaBean> listDynaBean = new ArrayList<>();
        for(Map<String,Object> map:list){
            DynaBean dynaBean = new DynaBean();
            dynaBean.setValues((Map<String, Object>) map.get("values"));
            dynaBean.table(tableCode);
            commonService.buildModelCreateInfo(dynaBean);
            listDynaBean.add(dynaBean);
        }
        if(listDynaBean.size()>0){
            metaService.insertBatch(listDynaBean);
        }
    }

    /**
     * 按树形表的SY_PATH层级从小到大排序
     * @param datalist
     * @return
     */
    public List<DynaBean> sort(List<DynaBean> datalist){
        if(datalist==null || datalist.size()==0){
            return datalist;
        }

        Map<String,Integer> map = new HashMap<>();
        for(DynaBean dynaBean:datalist){
            String path = dynaBean.getStr("SY_PATH");
            String id = dynaBean.getPkValue();
            Integer level = StringUtil.isNotEmpty(path)?path.split("/").length:0;
            map.put(id,level);
        }

        List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list, new Comparator(){
            @Override
            public int compare(Object o1, Object o2){
                return +((Comparable)((Map.Entry)(o1)).getValue()).compareTo(((Map.Entry)(o2)).getValue());
            }
        });

        map.clear();
        List<DynaBean> newList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : list) {
            String key = entry.getKey();
            for(DynaBean dynaBean:datalist){
                String id = dynaBean.getPkValue();
                if(key.equals(id)){
                    newList.add(dynaBean);
                    break;
                }
            }
        }
        return newList;

    }

    public void insertOrUpdate(List<Map<String,Object>> list,String tableCode,String uniquFieldCode){
        if(list!=null&&list.size()>0){
            List<DynaBean> listDynaBean = new ArrayList<>();
            for(int i=0;i<list.size();i++){
                Map<String,Object> map = list.get(i);
                DynaBean dynaBean = new DynaBean();
                dynaBean.setValues((Map<String, Object>) map.get("values"));
                dynaBean.table(tableCode);
                DynaBean dbData = metaService.selectOne(tableCode,ConditionsWrapper.builder().eq(uniquFieldCode,dynaBean.getStr(uniquFieldCode)));
                if(dbData==null){
                    commonService.buildModelCreateInfo(dynaBean);
                    listDynaBean.add(dynaBean);
                }else{
                    commonService.buildModelModifyInfo(dynaBean);
                    metaService.update(dynaBean,ConditionsWrapper.builder().eq(uniquFieldCode,dynaBean.getStr(uniquFieldCode)));
                }
            }
            if(listDynaBean.size()>0){
                metaService.insertBatch(listDynaBean);
            }
        }


    }
}
